<template>
  <div ref="Chart" class="charts" style="width: 100%; height: 400px" />
</template>

<script setup lang="ts">
import * as echarts from 'echarts';
import { useI18n } from 'vue-i18n';

const i18n = useI18n();

const timer = ref();
const Chart = ref();
const historyChart = shallowRef();

const props = defineProps<{
  hardwareName: string | number;
  historyData: Array<any>;
  selected: string;
  hardwareType: string | number;
}>();

const displayData = computed(() => {
  return props.historyData
    ? props.historyData.filter(({ timeStamp }: { timeStamp: string }) => {
        const lastDateTime = new Date(
          props.historyData[props.historyData.length - 1].timeStamp,
        );
        if (props.selected === '15 minutes')
          lastDateTime.setMinutes(lastDateTime.getMinutes() - 15);
        if (props.selected === '1 hour')
          lastDateTime.setHours(lastDateTime.getHours() - 1);
        if (props.selected === '12 hours')
          lastDateTime.setHours(lastDateTime.getHours() - 12);
        if (props.selected === '24 hours')
          lastDateTime.setHours(lastDateTime.getHours() - 24);
        if (props.selected === '48 hours')
          lastDateTime.setHours(lastDateTime.getHours() - 48);
        return new Date(timeStamp) > lastDateTime;
      })
    : [];
});

onMounted(() => {
  if (!displayData.value.length) return;
  historyChart.value = echarts.init(Chart.value);
  const title = props.hardwareName;

  let yAxis: (
    | {
        name: any;
        type: string;
        splitLine: { lineStyle: { color: string } };
        axisLabel: { formatter: (value: number) => string };
        axisLine: { show: boolean; lineStyle: { color: string } };
        splitArea: { show: boolean };
        max: number;
        nameTextStyle?: undefined;
      }
    | {
        name: string;
        type: string;
        splitLine: { lineStyle: { color: string } };
        nameTextStyle: { align: string; padding: number[] };
        axisLine: { show: boolean; lineStyle: { color: string } };
        splitArea: { show: boolean };
        max: number;
        axisLabel?: undefined;
      }
  )[];
  if (props.hardwareType === 'Memory')
    yAxis = [
      {
        name: i18n.t('pagePerformanceMonitor.usage'),
        type: 'value',
        splitLine: {
          lineStyle: {
            color: '#abcfe8',
          },
        },
        axisLabel: { formatter: (value: number) => value + '%' },
        axisLine: {
          show: false,
          lineStyle: {
            color: '#333',
          },
        },
        splitArea: {
          show: false,
        },
        max: 100,
      },
      {
        name:
          i18n.t('pagePerformanceMonitor.totalCapacity') +
          props.historyData[0].capacity +
          props.historyData[0].unit,
        type: 'value',
        splitLine: {
          lineStyle: {
            color: '#abcfe8',
          },
        },
        nameTextStyle: {
          align: 'left',
          padding: [0, -60],
        },
        axisLine: {
          show: false,
          lineStyle: {
            color: '#333',
          },
        },
        splitArea: {
          show: false,
        },
        max: 100,
      },
    ];
  else if (props.hardwareType === 'Disk')
    yAxis = [
      {
        name: i18n.t('pagePerformanceMonitor.usage'),
        type: 'value',
        splitLine: {
          lineStyle: {
            color: '#abcfe8',
          },
        },
        axisLabel: { formatter: (value: number) => value + '%' },
        axisLine: {
          show: false,
          lineStyle: {
            color: '#333',
          },
        },
        splitArea: {
          show: false,
        },
        max: 100,
      },
      {
        name:
          i18n.t('pagePerformanceMonitor.free') +
          ':' +
          props.historyData[0].free +
          props.historyData[0].freeUnit +
          '\n' +
          i18n.t('pagePerformanceMonitor.totalCapacity') +
          props.historyData[0].capacity +
          props.historyData[0].freeUnit,
        type: 'value',
        splitLine: {
          lineStyle: {
            color: '#abcfe8',
          },
        },
        nameTextStyle: {
          align: 'left',
          padding: [0, -60],
        },
        axisLine: {
          show: false,
          lineStyle: {
            color: '#333',
          },
        },
        splitArea: {
          show: false,
        },
        max: 100,
      },
    ];
  else
    yAxis = [
      {
        name: i18n.t('pagePerformanceMonitor.usage'),
        type: 'value',
        splitLine: {
          lineStyle: {
            color: '#abcfe8',
          },
        },
        axisLabel: { formatter: (value: number) => value + '%' },
        axisLine: {
          show: false,
          lineStyle: {
            color: '#333',
          },
        },
        splitArea: {
          show: false,
        },
        max: 100,
      },
    ];

  if (props.hardwareType !== 'NetInterface') {
    options = () => {
      return {
        title: {
          text: title,
          left: 'center',
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            lineStyle: {
              color: '#ddd',
            },
          },
          backgroundColor: 'rgba(233,233,233,1)',
          padding: [5, 10],
          textStyle: {
            color: '#7588E4',
          },
          extraCssText: 'box-shadow: 0 0 5px rgba(0,0,0,0.3)',
          valueFormatter: (value: number) => value.toFixed(2) + '%',
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            data: displayData.value.map(
              ({ timeStamp }: { timeStamp: string }) => {
                const date = timeStamp.split(' ')[0];
                const dateArr = date.match(
                  /(\d{4})-(\d{1,2})-(\d{1,2})/,
                ) as RegExpMatchArray;
                const [month, day] = [dateArr[2], dateArr[3]];

                const time = timeStamp.split(' ')[1];
                const timeArr = time.match(
                  /(\d{2}):(\d{2}):(\d{2})/,
                ) as RegExpMatchArray;
                const [hour, minute, second] = [
                  timeArr[1],
                  timeArr[2],
                  timeArr[3],
                ];
                return `${month}-${day} ${hour}:${minute}:${second}`;
              },
            ),
            axisLabel: {
              formatter: function (value: any) {
                if (props.selected === '15 minutes')
                  return (
                    value.split(' ')[1].split(':')[0] +
                    ':' +
                    value.split(' ')[1].split(':')[1]
                  );
                else if (props.selected === '1 hour')
                  return (
                    value.split(' ')[1].split(':')[0] +
                    ':' +
                    value.split(' ')[1].split(':')[1]
                  );
                else if (props.selected === '12 hours')
                  return (
                    value.split(' ')[1].split(':')[0] +
                    ':' +
                    value.split(' ')[1].split(':')[1]
                  );
                else if (props.selected === '24 hours')
                  return '        ' + value.split(' ')[0] + '        ';
                else if (props.selected === '48 hours')
                  return '        ' + value.split(' ')[0] + '        ';
              },
            },
          },
        ],
        yAxis: yAxis,
        series: [
          {
            name: i18n.t('pagePerformanceMonitor.usage'),
            type: 'line',
            data: displayData.value.map(
              ({ usage }: { usage: string }) => usage,
            ),
            lineStyle: {
              color: {
                type: 'linear',

                colorStops: [
                  {
                    offset: 1,
                    color: '#2acb04',
                  },
                ],
                globalCoord: false,
              },
              shadowColor: 'rgba(72,216,191, 0.3)',
              shadowBlur: 10,
              shadowOffsetY: 20,
            },
            symbol: 'none',
            itemStyle: {
              color: '#2acb04',
            },
            smooth: true,
          },
        ],
      };
    };
  } else {
    options = () => {
      return {
        title: {
          text: title,
          left: 'center',
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            lineStyle: {
              color: '#ddd',
            },
          },
          backgroundColor: 'rgba(233,233,233,1)',
          padding: [5, 10],
          textStyle: {
            color: '#7588E4',
          },
          extraCssText: 'box-shadow: 0 0 5px rgba(0,0,0,0.3)',
          valueFormatter: (value: number) => value.toFixed(2) + 'Mbps',
        },
        legend: {
          bottom: 20,
          orient: 'horizontal',
          data: [
            i18n.t('pagePerformanceMonitor.downSpeed'),
            i18n.t('pagePerformanceMonitor.upSpeed'),
          ],
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            data: displayData.value.map(
              ({ timeStamp }: { timeStamp: string }) => {
                const date = timeStamp.split(' ')[0];
                const dateArr = date.match(
                  /(\d{4})-(\d{1,2})-(\d{1,2})/,
                ) as RegExpMatchArray;
                const [month, day] = [dateArr[2], dateArr[3]];

                const time = timeStamp.split(' ')[1];
                const timeArr = time.match(
                  /(\d{2}):(\d{2}):(\d{2})/,
                ) as RegExpMatchArray;
                const [hour, minute, second] = [
                  timeArr[1],
                  timeArr[2],
                  timeArr[3],
                ];
                return `${month}-${day} ${hour}:${minute}:${second}`;
              },
            ),
            axisLabel: {
              formatter: function (value: any) {
                if (props.selected === '15 minutes')
                  return (
                    value.split(' ')[1].split(':')[0] +
                    ':' +
                    value.split(' ')[1].split(':')[1]
                  );
                else if (props.selected === '1 hour')
                  return (
                    value.split(' ')[1].split(':')[0] +
                    ':' +
                    value.split(' ')[1].split(':')[1]
                  );
                else if (props.selected === '12 hours')
                  return (
                    value.split(' ')[1].split(':')[0] +
                    ':' +
                    value.split(' ')[1].split(':')[1]
                  );
                else if (props.selected === '24 hours')
                  return '        ' + value.split(' ')[0] + '        ';
                else if (props.selected === '48 hours')
                  return '        ' + value.split(' ')[0] + '        ';
              },
            },
          },
        ],
        yAxis: [
          {
            name: i18n.t('pagePerformanceMonitor.speed'),
            type: 'value',
            splitLine: {
              lineStyle: {
                color: '#abcfe8',
              },
            },
            axisLabel: { formatter: (value: number) => value + 'M' },
            axisLine: {
              show: false,
              lineStyle: {
                color: '#333',
              },
            },
            splitArea: {
              show: false,
            },
          },
          {
            name:
              i18n.t('pagePerformanceMonitor.maxSpeed') +
              ':' +
              props.historyData[0].maxSpeed +
              props.historyData[0].unit,
            type: 'value',
            splitLine: {
              lineStyle: {
                color: '#abcfe8',
              },
            },
            nameTextStyle: {
              align: 'left',
              padding: [0, -100],
            },
            axisLine: {
              show: false,
              lineStyle: {
                color: '#333',
              },
            },
            splitArea: {
              show: false,
            },
            max: props.historyData[0].maxSpeed,
          },
        ],
        series: [
          {
            name: i18n.t('pagePerformanceMonitor.downSpeed'),
            type: 'line',
            data: displayData.value.map(
              ({ downSpeed }: { downSpeed: string }) => downSpeed,
            ),
            lineStyle: {
              color: {
                type: 'linear',

                colorStops: [
                  {
                    offset: 1,
                    color: '#2acb04',
                  },
                ],
                globalCoord: false,
              },
            },
            symbol: 'none',
            itemStyle: {
              color: '#2acb04',
            },
            smooth: true,
          },
          {
            name: i18n.t('pagePerformanceMonitor.upSpeed'),
            type: 'line',
            data: displayData.value.map(
              ({ upSpeed }: { upSpeed: string }) => upSpeed,
            ),
            lineStyle: {
              color: {
                type: 'linear',
                colorStops: [
                  {
                    offset: 1,
                    color: '#00b4f6',
                  },
                ],
                globalCoord: false,
              },
            },
            symbol: 'none',
            itemStyle: {
              color: '#00b4f6',
            },
            smooth: true,
          },
        ],
      };
    };
  }
  historyChart.value.setOption(options(), {
    notMerge: false,
    lazyUpdate: true,
    silent: false,
  });
  timer.value = setInterval(() => {
    historyChart.value.resize();
  }, 500);
});

let options = () => {};

onBeforeUnmount(() => {
  clearInterval(timer.value);
});

watch(
  () => props.selected,
  () => {
    historyChart.value.setOption(options(), {
      notMerge: false,
      lazyUpdate: true,
      silent: false,
    });
  },
);
</script>
